<template>
  <el-drawer
    title="标签分箱"
    size="60%"
    :visible.sync="drawerVisible"
    direction="rtl"
    :close-on-press-escape="false"
    :wrapperClosable="false"
    :destroy-on-close="true"
    :before-close="clearDrawer"
    custom-class="tag-drawer tag-binning-drawer"
  >
    <div class="drawer-wrap">
      <div class="drawer-content tag-scrollbar">
        <el-form :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
          <el-form-item label="标签名称" prop="tagId">
            <el-select v-model="editForm.tagId" filterable remote :remote-method="getTagNm" @change="changeTag">
              <el-option v-for="item in tagList" :key="item.tagId" :label="item.tagNm" :value="item.tagId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="取值类型" prop="valueType">
            <el-select v-model="editForm.valueType" disabled>
              <el-option label="---" value=""></el-option>
              <el-option
                v-for="item in $dictList('value_type')"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <template v-if="editForm.enumTag">
            <tag-content-header search refresh @toolFun="toolFun">
              <template #title>
                <span>枚举值列表</span>
              </template>
            </tag-content-header>
            <tag-table
              ref="table"
              @refresh="getList"
              :data="dataList"
              :loading="loading"
              :columns="columns"
              :params="params"
              :total="totalSize"
              selection
              rowKey="cdVal"
            >
            </tag-table>
          </template>
          <el-form-item prop="labGrps" label="分组规则" v-else>
            <config-range :target="editForm" @addRule="addRule" @removeRule="removeRule"></config-range>
          </el-form-item>
          <el-form-item label="填写默认值" prop="isDefaultValue">
            <!-- <el-input v-model="editForm.defaultValue" placeholder="请输入标签默认值,如不填则为空"></el-input> -->
            <el-radio-group v-model="editForm.isDefaultValue">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="editForm.isDefaultValue">
            <el-row :gutter="20" class="default-content">
              <el-col :span="10">
                <el-form-item
                  prop="tagDefaultValue"
                  :label="editForm.enumTag ? '枚举值' : '代码值'"
                  label-width="190px"
                >
                  <el-input v-model="editForm.tagDefaultValue"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item prop="description" label="描述" label-width="60px">
                  <el-input v-model="editForm.description"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </el-form>
      </div>
    </div>
    <div class="drawer-btns">
      <el-button @click="clearDrawer">关闭</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
  </el-drawer>
</template>
<script>
import configRange from './config-range'
export default {
  name: 'configDrawer',
  components: {
    configRange
  },
  data() {
    return {
      drawerVisible: false,
      drawerType: 'add',
      tagList: [],
      loading: false,
      dataList: [],
      columns: [
        {
          show: true,
          label: '枚举值',
          prop: 'cdVal',
          search: true,
          searchKey: '',
          align: 'center'
        },
        {
          show: true,
          label: '枚举值描述',
          prop: 'cdDesc',
          search: true,
          searchKey: '',
          align: 'center'
        }
      ],
      params: {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      },
      totalSize: 0,
      selectedVal: [],
      editForm: {
        tagId: '',
        tagNm: '',
        isDefaultValue: 0,
        tagDefaultValue: '',
        description: '',
        enumTag: '',
        valueType: '',
        labGrps: [
          {
            codeCd: '',
            codeDesc: '',
            valLft: '',
            valRit: ''
          }
        ]
      },
      editFormRules: {
        tagId: [{ required: true, message: '标签名称不能为空', trigger: 'change' }],
        tagDefaultValue: [{ required: true, message: '默认值不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    showDrawer(params) {
      this.drawerType = params.type
      this.editForm.tagId = params.tagId
      if (this.editForm.tagId) this.getDetail()
      this.drawerVisible = true
    },
    getTagNm(query) {
      if (!query) {
        this.tagList = []
        return
      }
      this.$ajax({
        url: this.$ajax.setUrl(`mon/monTagConfig/monTagList/${query}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.tagList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    changeTag(tagId) {
      const tag = this.tagList.find(item => item.tagId === tagId)
      if (tag) {
        this.editForm.tagNm = tag.tagNm
        this.editForm.enumTag = tag.enumTag
        this.editForm.valueType = tag.valueType
        this.getList()
      }
    },
    getDetail() {
      this.$ajax({
        url: this.$ajax.setUrl(`tag/tagDataBox/getTagBoxConfigInfo/${this.editForm.tagId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          const configJson = JSON.parse(data.data.tagConfigJson)
          this.editForm.tagNm = data.data.tagNm
          this.editForm.isDefaultValue = data.data.isDefaultValue
          this.editForm.valueType = data.data.tagType
          if (configJson.codeType === 'enum') {
            this.editForm.enumTag = 1
            this.selectedVal = configJson.codeConfig
            this.getList()
          } else {
            this.editForm.enumTag = 0
            this.editForm.labGrps = configJson.codeConfig
          }
          if (this.editForm.isDefaultValue) {
            this.editForm.tagDefaultValue = configJson.defaultValue.tagDefaultValue
            this.editForm.description = configJson.defaultValue.description
          }
          this.getTagNm(this.editForm.tagNm)
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getList() {
      this.loading = true
      this.params.queryParams.tagId = this.editForm.tagId
      this.$ajax({
        url: this.$ajax.setUrl('ast/astTagEnumVal/pageList'),
        method: 'get',
        params: this.$ajax.setParams(this.params)
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.dataList = data.data.records
          this.totalSize = data.data.totalSize
          this.selectedVal.forEach(v =>
            this.$nextTick(() => {
              let row = this.dataList.find(item => item.cdVal === v.codeCd)
              if (row) {
                let selectedRow = this.$refs.table.getSelectList()
                if (!selectedRow.find(item => item.cdVal === row.cdVal))
                  this.$refs.table.$refs.tagTable.toggleRowSelection(row)
              }
            })
          )
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    toolFun(operation) {
      switch (operation) {
        case 'search':
          // 搜索动作
          this.$refs['table'].searchToggle()
          break
        case 'refresh':
          // 刷新动作
          this.getList()
          break
      }
    },
    addRule(index) {
      this.editForm.labGrps.splice(index, 0, {
        codeCd: '',
        codeDesc: '',
        valLft: index >= 0 ? this.editForm.labGrps[index - 1].valRit : '',
        valRit: ''
      })
      this.$forceUpdate()
    },
    removeRule(index) {
      this.editForm.labGrps.splice(index, 1)
      this.$forceUpdate()
    },
    submit() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          let cdConfig = {
            codeType: 'other',
            codeConfig: this.editForm.labGrps
          }
          if (this.editForm.enumTag) {
            const eunmList = this.$refs.table.getSelectList()
            if (!eunmList.length) {
              this.$message.info('请选择枚举值！')
              return
            }
            cdConfig.codeType = 'enum'
            cdConfig.codeConfig = []
            eunmList.forEach(item => cdConfig.codeConfig.push({ codeCd: item.cdVal, codeDesc: item.cdDesc }))
          }
          if (this.editForm.isDefaultValue) {
            cdConfig.defaultValue = {
              tagDefaultValue: this.editForm.tagDefaultValue,
              description: this.editForm.description
            }
          }
          let params = {
            tagId: this.editForm.tagId,
            tagNm: this.editForm.tagNm,
            tagType: this.editForm.valueType,
            enumTag: this.editForm.enumTag,
            isDefaultValue: this.editForm.isDefaultValue
          }
          params.tagConfigJson = JSON.stringify(cdConfig)
          this.$ajax({
            url: this.$ajax.setUrl('tag/tagDataBox/saveTagBoxConfig'),
            method: this.drawerType === 'add' ? 'post' : 'put',
            data: this.$ajax.setData(params)
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.$message.success(data.msg)
              this.clearDrawer()
              this.$emit('refresh')
            } else {
              this.$message.error(data.data || data.msg)
            }
          })
        }
      })
    },
    clearDrawer() {
      this.drawerType = 'add'
      this.editForm.tagId = ''
      this.editForm.tagNm = ''
      this.editForm.isDefaultValue = 0
      this.editForm.enumTag = ''
      this.editForm.valueType = ''
      this.editForm.labGrps = [
        {
          codeCd: '',
          codeDesc: '',
          valLft: '',
          valRit: ''
        }
      ]
      this.dataList = []
      this.tagList = []
      this.selectedVal = []
      this.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.totalSize = 0
      this.drawerVisible = false
    }
  }
}
</script>

<style lang="scss">
.tag-binning-drawer {
  .default-content {
    .el-form-item__label {
      font-size: 14px !important;
      font-weight: normal !important;
    }
  }
}
</style>
